package com.zhitong.ztblog.controllers;

import com.zhitong.ztblog.entity.Comment;
import com.zhitong.ztblog.entity.PageInfo;
import com.zhitong.ztblog.services.ICommentService;
import com.zhitong.ztblog.utils.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class CommentContro {
    @Autowired
    private ICommentService commentService;

    @GetMapping("/comment/{bid}")
    public AjaxResponse getCommentByBid(@PathVariable(name = "bid")int bid){
        Comment[] comments = commentService.findByBid(bid);
        AjaxResponse success = AjaxResponse.success(comments);
        return success;
    }

    @PostMapping("/comment")
    public AjaxResponse postComment(@RequestBody Comment comment){
        try {
            commentService.insertComment(comment);
        } catch (Exception e) {
            AjaxResponse ajaxResponse=new AjaxResponse();
            ajaxResponse.setCode(500);
            ajaxResponse.setMessage("评论失败");
            return ajaxResponse;
        }
        return AjaxResponse.success();
    }

    @GetMapping("/comment/{currentPage}/{pageSize}")
    public AjaxResponse getCommentByPage(@PathVariable(name = "currentPage")int currentPage,@PathVariable(name = "pageSize")int pageSize){
        PageInfo pageInfo=new PageInfo(currentPage,pageSize,commentService.findCount());
        Comment[] comments = commentService.findCommentByPage(pageInfo);
        Map<String,Object> map=new HashMap<>();
        map.put("comments",comments);
        map.put("pageInfo",pageInfo);
        return AjaxResponse.success(map);
    }

    @DeleteMapping("/comment/{id}")
    public AjaxResponse delCommentById(@PathVariable(name = "id")int id){
        try {
            commentService.delCommentById(id);
        } catch (Exception e) {
            AjaxResponse ajaxResponse=new AjaxResponse();
            ajaxResponse.setCode(500);
            ajaxResponse.setMessage("删除失败");
            return ajaxResponse;
        }
        return AjaxResponse.success();
    }
}
